//
//  XYComposeController.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 15/12/26.
//  Copyright © 2015年 cn.weibo. All rights reserved.
//

import UIKit
import SVProgressHUD
class XYComposeController: UIViewController {
    
    private var toolBarAnimate: Bool = true
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        setUpNav()
    }
    @objc private func cancel() {
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    private func setUpNav() {
        
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_back_withtext" ,title: "取消", action: "cancel", target: self)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
        
        //添加textView
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        // 添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.width.equalTo(self.view)
            make.height.equalTo(44)
            make.bottom.equalTo(self.view)
            make.leading.equalTo(self.view)
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.view).offset(200)
            make.leading.equalTo(self.view).offset(8)
            make.width.equalTo(self.view).offset(-2 * 8)
            make.height.equalTo(pictureView.snp_width)
        }
        // 监听键盘弹出通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        // 监听表情选中通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedEmotion:", name: XYDidClickEmoticonBtnNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteEmoticon", name: XYDidClickDeleteBtnNotification, object: nil)
        
    }
    @objc private func deleteEmoticon() {
        
        textView.deleteBackward()
    }
    @objc private func didSelectedEmotion(noti:NSNotification) {
        let emoticon = noti.userInfo!["emoticon"]! as! XYEmoticon
        textView.insertEmoticon(emoticon)
    }
    private lazy var pictureView: XYComposePictureView = {
        let pictureView = XYComposePictureView()
        pictureView.didClickAddClosure = {[weak self] in
            self?.selectedPicture()
        }
        pictureView.backgroundColor = self.view.backgroundColor
        return pictureView
    }()
    private lazy var toolBar: XYComposeToolBar = {
        let toolBar = XYComposeToolBar(frame: CGRectZero)
        // 此处强引用  要弱引用self
        toolBar.composeToolBarBtnOnClickClosure = {[weak self](type) -> () in
            
            switch type {
            case .Picture:
                self?.selectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                self?.selectedemoticonBtn()
            case .Add:
                print("加号")
            }

        }
        return toolBar
    }()
    private func selectedemoticonBtn() {
        
        toolBarAnimate = false
        // 取消第一响应  并且设置切换键盘
        textView.resignFirstResponder()
        
        textView.inputView = (textView.inputView == nil) ? emoticonKeyboard : nil
        // 切换后成为第一响应者
        toolBarAnimate = true
        toolBar.isSystemKeyBoard = (textView.inputView == nil)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.1*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }
    }
    private func selectedPicture(){
        
        let vc = UIImagePickerController()
        vc.delegate = self
        presentViewController(vc, animated: true, completion: nil)
    }
    private lazy var textView: XYTextView = {
        let textView = XYTextView()
        textView.font = UIFont.systemFontOfSize(16)
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .OnDrag
        textView.delegate = self
        return textView
    }()
    // MARK: 懒加载控件
    // 表情键盘
    private lazy var emoticonKeyboard: XYEmoticonKeyBoard = {
        let keyboard = XYEmoticonKeyBoard()
        keyboard.backgroundColor = UIColor.redColor()
        keyboard.frame.size = CGSize(width: kSCREENWITH, height: 216)
        return keyboard
    }()
    private lazy var titleView: UILabel = {
        
        let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .Center
        if let name = XYUserAccountViewModel.sharedUserAccountViewModel.xUserAount?.screen_name {
            // 创建富文本文字
            let str = "发微博\n\(name)"
            // 这里要用可变富文本
            let attriStr = NSMutableAttributedString(string: str)
            let range = (str as NSString).rangeOfString(name)
            attriStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: range)
            attriStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            label.attributedText = attriStr
        }else {
            label.text = "发微博"
        }
        label.sizeToFit()

        return label
    }()
    private lazy var rightBtn: UIButton = {
        
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置不同状态的文字颜色
        
        btn.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        // 设置文字以及字体大小
        btn.setTitle("发送", forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        btn.frame.size = CGSize(width: 40, height: 30)
        btn.addTarget(self, action: "didClickSend", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    @objc private func didClickSend() {
        
        if pictureView.images.count == 0 {
            //发送文字
            sendText()
        }else{
            sendImage()
        }
    }
    private func sendText() {
        
        XYHTTPTool.sharedHttpTool.requestSendText(XYUserAccountViewModel.sharedUserAccountViewModel.accessToken!, status: textView.getEmoticonText) { (response, error) -> () in
            
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送失败")
                self.dismissViewControllerAnimated(true, completion: nil)
            }else{
                SVProgressHUD.showSuccessWithStatus("发送成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            }
            
        }
        
    }
    private func sendImage() {
        
        
        
    }
    @objc private func keyboardChangeFrame(noti:NSNotification) {
        
        
        if toolBarAnimate == false {
            return
        }
        // 取出结束时的fame
        if let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
            toolBar.snp_updateConstraints { (make) -> Void in
                make.bottom.equalTo(self.view).offset(endFrame.origin.y - kSCREENHEIGHT)
            }
            let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
            UIView.animateWithDuration(duration, animations: { () -> Void in
                self.toolBar.layoutIfNeeded()
            })
        }
    }
}
extension XYComposeController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
}
extension XYComposeController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        pictureView.addImage(image)
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
}